<template>
  <!-- 更新安全验收计划 -->
  <base-breadcrumb>
    <div class="about-master-container">
      <a-card :bordered="false">
        <title-name :title="pageType === 'look' ? '信息详情' : '基本信息'" />
        <a-form-model ref="form" :model="formInfo" :rules="rules">
          <a-row>
            <a-col :span="16">
              <a-form-model-item label="所属单位" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }">
                <b-input v-model="formInfo.viewName" disabled />
              </a-form-model-item>
            </a-col>
<!--            <a-col :span="8">-->
<!--              <a-form-model-item label="所属分公司" prop="branchComId">-->
<!--                <b-input v-model="formInfo.branchComName" disabled />-->
<!--              </a-form-model-item>-->
<!--            </a-col>-->
<!--            <a-col :span="8">-->
<!--              <a-form-model-item label="所属项目" prop="projectId">-->
<!--                <b-input v-model="formInfo.projectName" disabled />-->
<!--              </a-form-model-item>-->
<!--            </a-col>-->
            <a-col :span="8">
              <a-form-model-item label="计划月份" prop="planMonth">
                <b-input v-model="formInfo.planMonth" disabled />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-card>

      <a-card :bordered="false">
        <title-name title="安全验收计划表" />
        <div v-if="pageType !== 'look'" class="table-operateors mb20">
          <a-button type="primary" icon="plus" @click="openModal({},'add')">添加计划项</a-button>
          <!-- 导入 -->
          <ExcelImportButton
            ref="excelImportButton"
            icon="import"
            class="ml12"
            @handleSubmit="handleSubmit"
          />
          <!-- 导出模板 -->
          <export-mould class="ml12" template-code="安全验收计划模板.xlsx" icon="cloud-download" />
        </div>
        <s-table

          ref="table"
          :bordered="true"
          size="default"
          row-key="key"
          :columns="columns"
          :data="loadData"
          :alert="true"
          show-size-changer
          show-quick-jumper
          :show-pagination="false"
        >
          <template slot="index" slot-scope="text, record, index">
            {{ index + 1 }}
          </template>
          <template slot="operator" slot-scope="text, record">
            <div class="pub-table-list-action">
              <span class="base-btn" @click="openModal(record,'look')">查看</span>
              <template v-if="pageType !== 'look' && record.type !== 1">
                <!--            <template >-->
                <span class="base-btn" @click="openModal(record,'edit')">编辑</span>
                <a-popconfirm title="确定要删除?" @confirm="() => delItem(record)">
                  <span>删除</span>
                </a-popconfirm>
              </template>
            </div>

          </template>
        </s-table>
      </a-card>

      <div class="tool-btns page-btn-right-top">
        <a-button
          v-if="pageType !== 'look'"
          type="primary"
          :disabled="isSave"
          :loading="loading.SUBMITTED"
          @click="handleSave('SUBMITTED')"
        >
          提交
        </a-button>
        <a-button type="primary" @click="$close"> 关闭</a-button>
      </div>
    </div>

    <UpdatePlan :visible.sync="visible"
                @add="addRow"
                @edit="editRow"
                :form="modalData"
                :pageType="lPageType"
                :project-id="formInfo.projectId"
    />
  </base-breadcrumb>
</template>

<script>
import { STable } from '@/components'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import moment from 'moment'
import {
  acceptancePlanImport,
  addAcceptancePlan,
  deleteAcceptancePlan,
  getAcceptancePlanDetail,
  getAcceptancePlanList,
  updateAcceptancePlan
} from '@/api/safetySupervision/acceptancePlan'
import ExportMould from '@/components/ExportMould'
import UpdatePlan from '@/views/safetySupervision/safetyAcceptance/acceptancePlan/UpdatePlan'
import dayjs from 'dayjs' // 导出模板文件按钮

export default {
  name: 'a' + Date.now(),
  components: {
    SelectSubCompany,
    SelectProject,
    STable,
    ExportMould,
    UpdatePlan
  },
  data() {
    return {
      columns: [
        { title: '序号', dataIndex: 'index', width: 80, scopedSlots: { customRender: 'index' } },
        { title: '验收分类', dataIndex: 'acceptanceTypeName' },
        { title: '部位', dataIndex: 'acceptancePart' },
        { title: '等级', dataIndex: 'levelTypeName' },
        { title: '验收负责人', dataIndex: 'acceptanceResEmployeeName' },
        { title: '计划验收时间', dataIndex: 'acceptanceDate' },
        { title: '分包单位名称', dataIndex: 'subContractorName' },
        { title: '备注', dataIndex: 'remark' },
        { title: '填报人', dataIndex: 'creatorName' },
        { title: '填报时间', dataIndex: 'createTime' },
        {
          title: ' 操作',
          dataIndex: 'operator',
          width: 180,
          scopedSlots: { customRender: 'operator' }
        }
      ],
      loading: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false
      },
      id: '',
      isSave: false,
      visible: false,
      lPageType: 'add',
      modalData: {},
      rules: {
        branchComId: [{ required: true, message: '请选择分公司' }],
        projectId: [{ required: true, message: '请选择项目' }],
        planMonth: [{ required: true, message: '请选择月份' }]
      },

      formInfo: {
        id: null,
        itemDTO: [],
        project: { key: '', lable: '' },
        projectId: '',
        name: '',
        viewName: ''
      },
      loadData: () => {
        if (this.formInfo.itemDTO.length > 0) {
          return new Promise((resolve, reject) => {
            resolve({
              data: this.formInfo.itemDTO
            })
          })
        }
      },
      importCheck: {
        验收类别: 'acceptanceTypeName',
        验收部位: 'acceptancePart',
        等级: 'levelTypeName',
        计划验收时间: 'acceptanceDate',
        验收负责人: 'acceptanceResEmployeeName',
        '参与(英文逗号分隔)': 'userNames',
        分包单位名称: 'subContractorName',
        其他单位: 'otherDeptName',
        备注: 'remark'
      } // 导入字段对应
    }
  },
  computed: {
    pageType() {
      return this.$route.query.pageType || 'look'
    },
    isDisabled() {
      return this.pageType == 'edit'
    }
  },
  created() {
    this.id = this.$route.query.id
    this.$route.meta.title = this.id == '' ? '安全验收计划新增' : '安全验收计划编辑'
    // console.log(this.id)
  },
  mounted() {
    if (this.$route.query.id) {
      this.formInfo.id = this.$route.query.id
      this.getDetail()
    }
  },
  methods: {
    addRow(r) {
      this.formInfo.itemDTO.push(r)
      this.$refs.table.refresh(true)
    },
    editRow(r) {
      let resIndex = this.formInfo.itemDTO.findIndex(v => v.key === r.key)
      if (resIndex !== null) {
        this.formInfo.itemDTO[resIndex] = r
      }
      this.$refs.table.refresh(true)
    },
    disabledDate(current) {
      // Can not select days before today and today
      return current && current < moment().endOf('day')
    },
    disabledMonth(current) {
      return (
        (current && current < this.moment().startOf('month').subtract('month')) ||
        current > this.moment().endOf('month').subtract('month', -1).endOf('month')
      )
    },
    changeMouth() {
      if (this.pageType == 'add') {
        console.log(this.formInfo.planMonth.format('YYYY-MM'))
        this.isAddPlan()
        this.formInfo.name =
          this.formInfo.projectName + this.formInfo.planMonth.format('YYYY-MM') + '安全验收计划'
      }
    },

    async isAddPlan() {
      console.log(this.formInfo.planMonth)
      if (!this.formInfo.planMonth) return
      const [err, res] = await getAcceptancePlanList({ projectId: this.formInfo.projectId, isPermissions: '0' })
      let plan = res.data.filter(
        (i) =>
          i.projectId == this.formInfo.projectId && i.planMonth == this.formInfo.planMonth.format('YYYY-MM')
      )
      if (plan.length > 0) {
        this.$message.warning('该项目在该月份已有验收计划！')
        this.isSave = true
      } else {
        this.isSave = false
      }
    },
    delItem(data) {
      this.formInfo.itemDTO.forEach((item, idx) => {
        if (item.key == data.key) {
          this.formInfo.itemDTO.splice(idx, 1)
        }
      })
    },
    async getDetail() {
      this.$refs.table.localLoading = true
      const [err, res] = await getAcceptancePlanDetail({ id: this.formInfo.id })
      this.$refs.table.localLoading = false
      if (!err) {
        this.formInfo = { ...this.formInfo, ...res.data }
        this.formInfo.viewName = this.formInfo.branchComName + '/' + this.formInfo.projectName
      }
      this.formInfo.itemDTO.forEach((item, i) => {
        item.acceptanceTypeName = item.acceptanceType?.name
        item.key = i.toString()
      })
      this.$refs.table.refresh(true)
    },
    openModal(record = {}, pageType) {
      this.lPageType = pageType
      this.visible = true
      this.modalData = this.$clone(record)
    },
    validateForm() {
      let flag = false
      this.$refs.form.validate((valid) => {
        flag = valid
        if(!valid) {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
      return flag
    },
    async deleteAcceptancePlan(params) {
      const [err, res] = await deleteAcceptancePlan(params)
      if (!err) {
        this.$message.success('删除成功')
        this.handleClose()
      }
    },
    async deleteDraft() {
    },
    // 处理增、删、改操作
    async handleSave(status) {
      if (status !== 'DELETE' && !this.validateForm()) return
      if (this.loading[status]) return
      if (this.formInfo.itemDTO.length === 0) {
        this.$message.warning('请添加计划项')
        return
      }
      const params = { ...this.formInfo, auditStatus: status }
      const { pageType } = this.$route.query
      const fn = pageType === 'edit' ? updateAcceptancePlan : addAcceptancePlan
      const map = {
        DELETE: deleteAcceptancePlan,
        DRAFT: fn,
        SUBMITTED: fn
      }
      if (status === 'DELETE') {
        let that = this
        this.$confirm({
          title: '温馨提示',
          content: '确定是否删除数据？',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk: () => {
            return that.deleteAcceptancePlan(params)
          }
        })
      } else {
        this.loading[status] = true
        const [err, res] = await map[status](params)
        if (!err) {
          this.$message.success('操作成功')
          this.$close()
        }
        this.loading[status] = false
      }
    },
    /**
     * 导入记录
     */
    async handleSubmit(e) {
      this.$console(e)
      let form = []
      for (let index in e) {
        console.log(index)
        form.push({})
        let keys = e[index]
        let listItem = form[index]
        // 校验excel的表头数量
        if (
          Object.keys(keys)?.length >= 7
        ) {
          // 校验excel的表头字段
          let tempImportCheck = {
            验收类别: 'acceptanceTypeName',
            验收部位: 'acceptancePart',
            等级: 'levelTypeName',
            计划验收时间: 'acceptanceDate',
            验收负责人: 'acceptanceResEmployeeName',
            '参与(英文逗号分隔)': 'userNames'
          }
          for (let i in tempImportCheck) {
            let englishKey = tempImportCheck[i]
            let k = Object.keys(keys)
            if (!k.includes(i)) {
              return this.$message.warning(`${i}缺失`)
            } else {
              listItem[englishKey] = keys[i]
            }
          }

          let r = false
          if (keys['其他单位']) {
            r = true
            listItem['otherDeptName'] = keys['其他单位']
          }
          if (keys['分包单位名称']) {
            r = true
            listItem['subContractorName'] = keys['分包单位名称']
          }
          if (!r) return this.$message.warning('分包单位名称\\其他单位 缺失')

          if (keys['备注']) {
            listItem['remark'] = keys['备注']
          }

          listItem.creatorName = this.$userInfo().name
          listItem.type = 0
          listItem.createTime = this.$dateFormat(Date.now(), 'D')

          if (dayjs(listItem['acceptanceDate']).isBefore(dayjs().date(1).subtract(1, 'day'))) {
            return this.$noticeWarning('计划验收时间不能小于本月')
          }

        } else {
          this.$message.warning('数据不完整')
          return
        }
      }
      this.$refs.table.localLoading = true
      this.$console(form)
      let res = await acceptancePlanImport({
        branchComId: this.formInfo.branchComId,
        projectId: this.formInfo.projectId,
        planMonth: this.formInfo.planMonth,
        itemDTO: form
      })
      this.$refs.table.localLoading = false
      if (res.code === this.SUCCESS_CODE) {
        this.formInfo.itemDTO = this.formInfo.itemDTO.concat(res.data.itemDTO)
        this.$refs.table.refresh(true)
      }
    }
  }
}
</script>

<style lang="less" scoped>
@deep: ~'>>>';
.page-header {
  .header-row {
    display: flex;

    .flex-content {
      flex: auto;
    }

    .divider {
      margin: 0 12px;
    }

    .expand-btn {
      margin-left: 8px;
      font-size: 14px;
    }
  }
}

.page-body {
  .table-operateors {
    .ant-btn + .ant-btn {
      margin-left: 12px;
    }
  }
}

.tool-btns {
  display: flex;
  justify-content: flex-end;

  @{deep} .ant-btn + .ant-btn {
    margin-left: 12px;
  }
}
</style>
